﻿using DevExpress.Persistent.Base;
using DevExpress.Persistent.BaseImpl;
using DevExpress.Xpo;
using EasyXaf.TreeListEditors;
using System.ComponentModel;

namespace EasyXaf.Sample.Module.BusinessObjects;

[DefaultClassOptions]
[ImageName("BO_Department")]
public class Department : BaseObject, ITreeObject<Guid>
{
    [Browsable(false)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public Guid Id => Oid;

    [Browsable(false)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public Guid? ParentId => Parent?.Oid;

    [Browsable(false)]
    public string TreeCode
    {
        get => GetPropertyValue<string>(nameof(TreeCode));
        set => SetPropertyValue(nameof(TreeCode), value);
    }

    public string Name
    {
        get => GetPropertyValue<string>(nameof(Name));
        set => SetPropertyValue(nameof(Name), value);
    }

    [Association]
    public Department Parent
    {
        get => GetPropertyValue<Department>(nameof(Parent));
        set
        {
            var parent = value;
            while (parent != null)
            {
                if (parent == this)
                {
                    return;
                }
                parent = parent.Parent;
            }
            SetPropertyValue(nameof(Parent), value);
        }
    }

    [Association]
    public XPCollection<Department> Children
    {
        get => GetCollection<Department>(nameof(Children));
    }

    string ITreeObjectImage.Image => "BO_Folder";

    public Department(Session session)
        : base(session)
    {
    }
}
